package config

import (
	"flag"
	"fmt"
	"os"
	"testing"

	"gitee.com/xiawucha365/sago.v2/core/util"
)

//=========flag
type FlagOption struct {
	Debug  bool
	Conf   string
	RunEnv string
	Beans  string
}

func NewFlagOption() (opt *FlagOption) {
	opt = new(FlagOption)
	flag.BoolVar(&opt.Debug, "debug", false, "是否开启debug模式")
	flag.StringVar(&opt.Conf, "conf", "", "配置文件目录(绝对目录)")
	flag.StringVar(&opt.RunEnv, "env", RunEnvDev, "运行环境 dev prod")
	flag.StringVar(&opt.Beans, "beans", "all", "开启组件")

	//单元测试兼容
	typeos := os.Args[0][len(os.Args[0])-4 : len(os.Args[0])]
	if typeos == "test" {
		testing.Init()
	}

	flag.Parse()

	fileName := opt.Conf
	if opt.Conf == "" {
		if opt.RunEnv == RunEnvDev {
			fileName = "/etc/dev.toml"
		}
		if opt.RunEnv == RunEnvProd {
			fileName = "/etc/prod.toml"
		}

	}

	fileNameFull := ""
	for _, path := range getPaths(util.GetExecutePath()) {
		fileNameFull = path + fileName
		if opt.Debug {
			fmt.Println(fileNameFull)
		}
		if util.FileExist(fileNameFull) {
			opt.Conf = fileNameFull
			break
		} else {
			fileNameFull = ""
		}
	}
	if fileNameFull == "" {
		panic(fileName + " 不存在")
	}

	return
}

func getPaths(path string) []string {
	paths := make([]string, 4)
	paths = append(paths, path+"/./")
	paths = append(paths, path+"/..")
	paths = append(paths, path+"/../..")
	paths = append(paths, path+"/../../..")
	return paths
}
